package leetcode002;

/**
 * https://leetcode.cn/problems/add-two-numbers/description/
 * 给你两个 非空 的链表，表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的，并且每个节点只能存储 一位 数字。
 *
 * 请你将两个数相加，并以相同形式返回一个表示和的链表。
 *
 * 你可以假设除了数字 0 之外，这两个数都不会以 0 开头。
 */
public class Study002 {

    //Definition for singly-linked list.
    public static class ListNode {
        int val;
        ListNode next;
        public ListNode() {}
        public ListNode(int val) { this.val = val; }
        public ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        final int invalidNum = -1;
        //进位用的变量
        int nextVal = 0;
        //返回用的节点
        ListNode result = new ListNode(invalidNum);
        //当前节点
        ListNode cur = result;
        while (l1 != null || l2 != null || nextVal != 0) {

            int l1val = (l1 != null)? l1.val: 0;
            int l2val = (l2 != null)? l2.val: 0;
            int tempVal = l1val + l2val;
            tempVal += nextVal;
            if ( tempVal >= 10 ) {
                nextVal = 1;//进位
                tempVal = tempVal - (tempVal/ 10* 10);
            } else {
                nextVal = 0;
            }

            if (cur.val == invalidNum) {
                cur.val = tempVal;
            } else {
                cur.next = new ListNode(tempVal);
                cur = cur.next;
            }

            if (l1 != null){
                l1 = l1.next;
            }
            if (l2 != null){
                l2 = l2.next;
            }
        }
        return result;
    }


    public static void main(String[] args) {
        Study002 study002 = new Study002();
        ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3)));
        ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4)));
        ListNode result = study002.addTwoNumbers(l1, l2);
        while (result != null) {
            System.out.println(result.val);
            result = result.next;
        }
    }

}
